﻿using AsyncLoggers.Exceptions;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.Unity;

namespace AsyncLoggers.EnterpriseLibrary
{
    /// <summary>
    /// A shortcut for accessing some of the asynchronous
    /// logging functionality related to Enterprise Library logging block
    /// </summary>
    public static class EntepriseAsyncLoggers
    {
        /// <summary>
        /// Swaps current implementation of <see cref="LogWriter"/> for an asynchronous version
        /// </summary>
        /// <exception cref="FailedToSwapLoggerException"></exception>
        public static void SwapSynchronousLoggerForAsynchronous()
        {
            var currentlyRegisteredLogWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

            if (currentlyRegisteredLogWriter is AsyncLogWriter)
            {
                throw new FailedToSwapLoggerException(
                    "Reconfiguration has failed: asynchronous logger is already in place");
            }

            // TODO: is this even accurate enough? Can't we just swap one thing without rebuilding the container?

            var container = new UnityContainer();

            container.AddExtension(new EnterpriseLibraryCoreExtension());

            container.RegisterInstance<LogWriter>(new AsyncLogWriter(currentlyRegisteredLogWriter));

            var locator = new UnityServiceLocator(container);

            EnterpriseLibraryContainer.Current = locator;
        }
    }
}